
package com.xunce.xcworkservice.jwt;

import com.xunce.xcworkservice.Enums.Enums;
import com.xunce.xcworkservice.entity.AccountToken;
import com.xunce.xcworkservice.entity.Account;
import com.xunce.xcworkservice.service.ShiroService;
import com.xunce.xcworkservice.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.util.Set;

/**
 * @author yanlong.guo
 */
@Component
@RequiredArgsConstructor
public class JWTRealm extends AuthorizingRealm {

    private final ShiroService shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Account user = (Account) principals.getPrimaryPrincipal();
        Integer userId = user.getAccountId();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        AccountToken tokenEntity = shiroService.queryByToken(accessToken);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        Account user = shiroService.queryUser(tokenEntity.getUserId());
        //账号锁定
        if(user == null || user.getState().equals(Enums.AccountState.DISABLED.getValue())){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        userInfoVo.setToken(accessToken);

        //通过验证更新使用时间
        shiroService.updateTokenUsedAt(tokenEntity.getId());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfoVo, accessToken, getName());
        return info;
    }
}
